<template>
  <div class="brand-container">
    <div class="toolbar">
      <el-button type="success" @click="handleAdd">新增品牌</el-button>
    </div>

    <!-- 品牌表格 -->
    <art-table
      :data="tableData"
      :loading="loading"
      :pagination="true"
      :total="total"
      :current-page="searchData.page"
      :page-size="searchData.pageSize"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      highlight-current-row
      show-header-background
    >
      <el-table-column prop="brandName" label="品牌名称" min-width="150" />
      <el-table-column prop="brandLogo" label="品牌Logo" min-width="150" align="center">
        <template #default="scope">
          <el-image
            :src="scope.row.brandLogo"
            class="brand-logo"
            fit="cover"
            lazy
            :preview-src-list="[scope.row.brandLogo]"
            preview-teleported
          />
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" min-width="180" />
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="scope">
          <div class="table-actions">
            <button-table type="edit" @click="handleEdit(scope.row)" />
            <el-popconfirm title="确认删除此品牌吗？" @confirm="handleDelete(scope.row.id)">
              <template #reference>
                <button-table type="delete" @click.stop="() => {}" />
              </template>
            </el-popconfirm>
          </div>
        </template>
      </el-table-column>
    </art-table>

    <!-- 编辑/新增对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增品牌' : '编辑品牌'"
      width="40%"
      center
      :close-on-click-modal="false"
      @closed="onDialogClosed"
    >
      <el-form ref="brandFormRef" :model="brandForm" :rules="brandFormRules" label-width="100px">
        <el-form-item label="品牌名称" prop="brandName">
          <el-input v-model="brandForm.brandName" placeholder="请输入品牌名称" maxlength="50" />
        </el-form-item>
        <el-form-item label="品牌Logo" prop="brandLogo">
          <el-upload
            class="logo-uploader"
            action="/api/file/upload"
            :show-file-list="false"
            :on-success="handleLogoSuccess"
            :before-upload="beforeLogoUpload"
          >
            <img v-if="brandForm.brandLogo" :src="brandForm.brandLogo" class="logo" />
            <el-icon v-else class="logo-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">点击上传品牌Logo，建议尺寸200*200像素</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitBrandForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage } from 'element-plus'
  import type { FormInstance, UploadProps } from 'element-plus'
  import { Plus } from '@element-plus/icons-vue'
  import { getBrandList, addBrand, updateBrand, deleteBrand, getBrandById } from '@/api/brandApi'
  import { ApiStatus } from '@/utils/http/status'
  import type { BrandType } from '@/api/model/brandModel'

  // 搜索数据
  const searchData = reactive({
    page: 1,
    pageSize: 10
  })

  // 表格数据
  const tableData = ref<BrandType[]>([])
  const total = ref(0)
  const loading = ref(false)

  // 对话框相关
  const dialogVisible = ref(false)
  const dialogType = ref<'add' | 'edit'>('add')

  // 表单数据
  const brandFormRef = ref<FormInstance | null>(null)
  const brandForm = reactive({
    id: undefined as number | undefined,
    brandName: '',
    brandLogo: ''
  })

  const brandFormRules = {
    brandName: [
      { required: true, message: '请输入品牌名称', trigger: 'blur' },
      { min: 1, max: 50, message: '品牌名称长度在 1 到 50 个字符', trigger: 'blur' }
    ],
    brandLogo: [{ required: true, message: '请上传品牌Logo', trigger: 'change' }]
  }

  // 初始化数据
  onMounted(() => {
    getBrandListData()
  })

  // 获取品牌列表
  const getBrandListData = async () => {
    loading.value = true
    try {
      const res = await getBrandList(searchData)
      if (res.code === ApiStatus.success) {
        tableData.value = res.data.list || []
        total.value = res.data.total || 0
      } else {
        ElMessage.error(res.message || '获取品牌列表失败')
        tableData.value = []
        total.value = 0
      }
    } catch (error) {
      ElMessage.error('获取品牌列表失败')
      console.error(error)
      tableData.value = []
      total.value = 0
    } finally {
      loading.value = false
    }
  }

  // 处理分页大小变化
  const handleSizeChange = (size: number) => {
    searchData.pageSize = size
    getBrandListData()
  }

  // 处理当前页变化
  const handleCurrentChange = (current: number) => {
    searchData.page = current
    getBrandListData()
  }

  // 新增品牌
  const handleAdd = () => {
    dialogType.value = 'add'
    brandForm.id = undefined
    brandForm.brandName = ''
    brandForm.brandLogo = ''
    dialogVisible.value = true
  }

  // 编辑品牌
  const handleEdit = async (row: BrandType) => {
    if (!row.id) return

    try {
      const res = await getBrandById({ id: row.id })
      if (res.code === ApiStatus.success) {
        dialogType.value = 'edit'
        brandForm.id = res.data.id
        brandForm.brandName = res.data.brandName || ''
        brandForm.brandLogo = res.data.brandLogo || ''
        dialogVisible.value = true
      } else {
        ElMessage.error(res.message || '获取品牌详情失败')
      }
    } catch (error) {
      ElMessage.error('获取品牌详情失败')
      console.error(error)
    }
  }

  // 删除品牌
  const handleDelete = async (id?: number) => {
    if (!id) return

    try {
      const res = await deleteBrand({ id })
      if (res.code === ApiStatus.success) {
        ElMessage.success('删除成功')
        getBrandListData()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败')
      console.error(error)
    }
  }

  // Logo上传成功处理
  const handleLogoSuccess: UploadProps['onSuccess'] = (response) => {
    if (response.code === ApiStatus.success) {
      brandForm.brandLogo = response.data
      ElMessage.success('上传成功')
    } else {
      ElMessage.error(response.message || '上传失败')
    }
  }

  // Logo上传前处理
  const beforeLogoUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
      ElMessage.error('品牌Logo只能是 JPG 或 PNG 格式!')
      return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
      ElMessage.error('品牌Logo大小不能超过 2MB!')
      return false
    }
    return true
  }

  // 提交表单
  const submitBrandForm = async () => {
    if (!brandFormRef.value) return

    try {
      await brandFormRef.value.validate()

      let res
      if (dialogType.value === 'edit' && brandForm.id) {
        // 编辑品牌
        res = await updateBrand({
          id: brandForm.id,
          brandName: brandForm.brandName,
          brandLogo: brandForm.brandLogo
        })
      } else {
        // 新增品牌
        res = await addBrand({
          brandName: brandForm.brandName,
          brandLogo: brandForm.brandLogo
        })
      }

      if (res.code === ApiStatus.success) {
        ElMessage.success(dialogType.value === 'edit' ? '编辑成功' : '新增成功')
        dialogVisible.value = false
        getBrandListData()
      } else {
        ElMessage.error(res.message || (dialogType.value === 'edit' ? '编辑失败' : '新增失败'))
      }
    } catch (error) {
      console.error(error)
    }
  }

  // 对话框关闭时
  const onDialogClosed = () => {
    if (brandFormRef.value) {
      brandFormRef.value.clearValidate()
    }
  }
</script>

<style lang="scss" scoped>
  .brand-container {
    padding: 20px;

    .toolbar {
      margin-bottom: 20px;
      text-align: right;
    }

    .brand-logo {
      width: 60px;
      height: 60px;
      border-radius: 4px;
    }

    .table-actions {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
      align-items: center;
      justify-content: center;

      :deep(.btn-text) {
        margin-right: 0 !important;
      }
    }

    .dialog-footer {
      display: flex;
      gap: 10px;
      justify-content: flex-end;
    }

    .logo-uploader .logo {
      display: block;
      width: 120px;
      height: 120px;
      border-radius: 6px;
    }

    .logo-uploader-icon {
      width: 120px;
      height: 120px;
      font-size: 28px;
      line-height: 120px;
      color: #8c939d;
      text-align: center;
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
    }

    .upload-tip {
      margin-top: 5px;
      font-size: 12px;
      color: #999;
    }
  }

  // 响应式适配
  @media screen and (width <= 768px) {
    .brand-container {
      padding: 10px;

      .toolbar {
        text-align: center;
      }

      .table-actions {
        flex-direction: column;
        gap: 5px;
      }

      .logo-uploader-icon,
      .logo-uploader .logo {
        width: 80px;
        height: 80px;
        line-height: 80px;
      }
    }
  }
</style>
